package cn.yuanqiao.archive.cqbctuisong.service.impl;
/**
 * @author 赵常飞
 * @date 2024/6/29 17:51
 */

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaFolder;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.cqbctuisong.domain.TenantCqbcPush;
import cn.yuanqiao.archive.cqbctuisong.mapper.CqbcTuiSongMapper;
import cn.yuanqiao.archive.cqbctuisong.service.ICqbcTuiSongService;
import cn.yuanqiao.archive.danganzhengli.service.impl.HandOverReceiveServiceImpl;
import cn.yuanqiao.archive.danganzhengli.utils.webServiceHttp;
import cn.yuanqiao.archive.detection.service.IDetectionObjectService;
import cn.yuanqiao.archive.webservice.utils.WebServiceFileUtils;
import cn.yuanqiao.common.constant.ServiceNameConstants;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.ZipUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: 赵常飞
 *@Date: 2024/6/29 17:51
 *@Description:
 *@Note:
 */
@Service
public class CqbcTuiSongServiceImpl implements ICqbcTuiSongService {


    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private ITenantCateMdataListService tenantMdataListService;
    @Autowired
    private CqbcTuiSongMapper cqbcTuiSongMapper;
    @Autowired
    private HandOverReceiveServiceImpl handOverReceiveService;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private IDetectionObjectService detectionObjectService;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    TransactionDefinition transactionDefinition;
    @Value("${ITEM_BGQX}")
    private String itembgqx;

    @Value("${cqbc.serviceIp}")
    private String serviceIp;
    @Override
    public void pushtocqbc(JSONObject json) throws  IOException {
        JSONArray ids = json.getJSONArray("ids");
        Long categoryId=json.getLong("categoryId");
        TenantCategory category=new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        String tenantCode=SecurityUtils.getLoginUser().getSysUser().getTenantCode();
        //推送
        //通过Java应用获取当前服务部署所在机器ip

        String url="http://"+serviceIp+"/webservice/CqbcWebservice?wsdl";
        //构造xml参数
        StringBuffer sb = new StringBuffer();
        TransactionStatus transactionStatus = null;
        TenantCqbcPush tenantCqbcPush=new TenantCqbcPush();
        List<Map<String,String>> datalist=cqbcTuiSongMapper.getStatebyids(ids,tenantCqbcPush.getTableName());
        for (int i = 0; i <datalist.size(); i++) {
            if("四性检测通过".equals(datalist.get(i).get("STATE"))||"推送失败".equals(datalist.get(i).get("STATE"))){
                //手动开启事务
                transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
                JSONObject transferjson=new JSONObject();
                String dataid=String.valueOf(datalist.get(i).get("DATA_ID"));
                File file=new File(datalist.get(i).get("PATH"));
                String name=file.getName().substring(0,file.getName().lastIndexOf("."));
                transferjson.put("name",name);
                transferjson.put("size",file.length());
                transferjson.put("format","zip");
                transferjson.put("fonds",tenantCategory.getFondsCode());
                transferjson.put("category",categoryId);
                transferjson.put("dh",name);
                transferjson.put("title",name);
                transferjson.put("tenantCode",tenantCode);
                transferjson.put("biaoshi",dataid);
                transferjson.put("zlfs",tenantCategory.getType());
                transferjson.put("saveTime",getSaveTime(tenantCategory,dataid));
                String file2base64="";
                file2base64=WebServiceFileUtils.fileToBase64(file);
                sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body>" +
                        "<ns1:CqbcSaveArchive soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
                        "xmlns:ns1=\"http://service.webservice.cqbc.yuanqiao.cn\">" +
                        "<paketInfo xsi:type=\"xsd:string\">"+transferjson+"</paketInfo>" +
                        "<file2base64 xsi:type=\"xsd:string\">"+file2base64+"</file2base64>" +
                        "</ns1:CqbcSaveArchive></soapenv:Body></soapenv:Envelope>");
                try {
                    String returnmsg = webServiceHttp.sendWebService(url, "CqbcWebservice", "CqbcSaveArchive", sb);
                    System.out.println(returnmsg);
                    JSONObject returnjson=JSONObject.parseObject(returnmsg);
                    if("success".equals(returnjson.getString("msg"))){
                        tenantCqbcPush.setState("推送成功");
                    }else{
                        tenantCqbcPush.setState("推送失败");
                    }
                    tenantCqbcPush.setDataId(Long.parseLong(dataid));
                    tenantCqbcPush.setPusher(SecurityUtils.getLoginUser().getUserId());
                    Date date=new Date();
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    tenantCqbcPush.setPushTime(sdf.format(date));
                    cqbcTuiSongMapper.update(tenantCqbcPush,tenantCqbcPush.getTableName());
                    //修改档案的CQBC_STATE
                    StringBuffer dabf=new StringBuffer();
                    String dafoldertable=new TenantYqdaFolder().getTableName();
                    String TenantItemFolder=new TenantYqdaFolder().getTableName();
                    if(0==tenantCategory.getType()){
                        dabf.append("update "+tenantCode+"_YQDA set CQBC_STATE=1 where da_id="+dataid+";");
                        dabf.append("update "+tenantCategory.getFileTableName()+" set CQBC_STATE=1 where id="+dataid+";");
                    }else if(1==tenantCategory.getType()){
                        dabf.append("update "+tenantCode+"_YQFOLDER set CQBC_STATE=1 where folder_id="+dataid+";");
                        dabf.append("update "+tenantCategory.getFolderTableName()+" set CQBC_STATE=1 where id="+dataid+";");
                        dabf.append("update "+tenantCode+"_YQDA set CQBC_STATE=1 where da_id in(select da_id from "+dafoldertable+" where folder_id="+dataid+");");
                        dabf.append("update "+tenantCategory.getFileTableName()+" set CQBC_STATE=1 where id in(select da_id from "+dafoldertable+" where folder_id="+dataid+");");
                    }else if(3==tenantCategory.getType()){
                        dabf.append("update "+tenantCode+"_YQITEM set CQBC_STATE=1 where item_id="+dataid+";");
                        dabf.append("update "+tenantCategory.getItemTableName()+" set CQBC_STATE=1 where id="+dataid+";");
                        dabf.append("update "+tenantCode+"_YQFOLDER set CQBC_STATE=1 where folder_id in(select folder_id from "+TenantItemFolder+" where item_id=" +dataid+");");
                        dabf.append("update "+tenantCategory.getFolderTableName()+" set CQBC_STATE=1 where id in(select folder_id from "+TenantItemFolder+" where item_id="+dataid+");");
                        dabf.append("update "+tenantCode+"_YQDA set CQBC_STATE=1 where da_id in(select da_id from "+dafoldertable+" where folder_id in(select folder_id from "+TenantItemFolder+" where item_id="+dataid+"));");
                        dabf.append("update "+tenantCategory.getFileTableName()+" set CQBC_STATE=1 where id in(select da_id from "+dafoldertable+" where folder_id in(select folder_id from "+TenantItemFolder+" where item_id="+dataid+"));");
                    }
                    cqbcTuiSongMapper.updatesql(dabf.toString());
                    sb=new StringBuffer();
                    dataSourceTransactionManager.commit(transactionStatus);
                } catch (Exception e) {
                    e.printStackTrace();
                    if (transactionStatus != null) {
                        dataSourceTransactionManager.rollback(transactionStatus);
                    }
                    continue;
                }
            }else{
                sb=new StringBuffer();
                continue;
            }
        }

    }

    private String getSaveTime(TenantCategory tenantCategory, String dataid) {
        if(0==tenantCategory.getType()){
            System.out.println("itembgqx===="+itembgqx);
            return cqbcTuiSongMapper.getbgqx(tenantCategory.getFileTableName(),dataid);
        }else if(1==tenantCategory.getType()){
            return cqbcTuiSongMapper.getbgqx(tenantCategory.getFolderTableName(),dataid);
        }else if(3==tenantCategory.getType()){
            return itembgqx;
        }
        return null;
    }

    @Override
    public List<Map<String, String>> getthbytreenode(JSONObject json) {
        Long categoryId = json.getLong("categoryId");
        Long menuId = json.getLong("menuId");
        String subTableName = json.getString("subTableName");
        JSONObject cjson=new JSONObject();
        cjson.put("categoryId",categoryId);
        cjson.put("menuId",menuId);
        String tenantCode= SecurityUtils.getLoginUser().getSysUser().getTenantCode();
        TenantCategory category=new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        int mdatatype = -1;
        if (null!=subTableName&&!"".equals(subTableName)){//有层级信息
            String type=subTableName.substring(subTableName.length()-3,subTableName.length()-2);
            if("F".equalsIgnoreCase(type)){//档案层
                mdatatype=0;
                cjson.put("level","jian");
            }else if("V".equalsIgnoreCase(type)){//案卷层
                mdatatype = 1;
                cjson.put("level","juan");
            }else if("X".equalsIgnoreCase(type)){//项目层
                mdatatype=3;
                cjson.put("level","xiangmu");
            }else if("E".equalsIgnoreCase(type)){//电子文件层
                mdatatype=2;
                cjson.put("level","efile");
            }
        }else{//只有门类时,获取最高一级
            if(tenantCategory.getType()==0){
                mdatatype=0;
                cjson.put("level","jian");
                subTableName=tenantCategory.getFileTableName();
            }else if(tenantCategory.getType()==1){
                mdatatype = 1;
                cjson.put("level","juan");
                subTableName=tenantCategory.getFolderTableName();
            }else if(tenantCategory.getType()==2){
                mdatatype=2;
                cjson.put("level","efile");
                subTableName=tenantCategory.getEfileTableName();
            }else if(tenantCategory.getType()==3){
                mdatatype=3;
                cjson.put("level","xiangmu");
                subTableName=tenantCategory.getItemTableName();
            }
        }

        List<Map<String, String>> getshowfield = tenantMdataListService.getshowfield(cjson);
        //不一定设置了长期保存状态,设置了也不一定在第一个,手动修改
        if(2!=mdatatype){
            for (int i = getshowfield.size()-1; i >=0 ; i--) {
                String fieldname=getshowfield.get(i).get("FIELD_NAME");
                if("CQBC_STATE".equals(fieldname)){
                    getshowfield.remove(i);
                }
                System.out.println(i);
            }
            Map<String,String> cqbcState=cqbcTuiSongMapper.getfield(new TenantMdataList().getTableName(),new TenantCategory().getTableName(),categoryId,mdatatype) ;
            if(null==cqbcState){
                throw new ServiceException("此门类缺少CQBC_STATE字段!");
            }
            Map map=new HashMap(1<<4);
            map.put("TH_WIDTH",null);
            map.put("FIELD_CAPTION","当前状态");
            map.put("SHOWTYPE","1");
            map.put("FIELD_NAME","(select state from "+new TenantCqbcPush().getTableName()+" where data_id="+subTableName+".id) as CQBCPUSHSTATE");
            map.put("TH_ALIGN",null);
            map.put("COL_WIDTH",null);
            getshowfield.add(0,map);
            getshowfield.add(0,cqbcState);
        }
        return getshowfield;
    }

    @Override
    public void plpakeage(JSONObject json) {
        JSONArray ids = json.getJSONArray("ids");
        Long categoryId=json.getLong("categoryId");
        TenantCategory category=new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        int type=tenantCategory.getType();
        String cspath = sysConfigService.selectConfigByKey("YQ_CQBC_PUSH");
        TenantCqbcPush tenantCqbcPush = new TenantCqbcPush();
        tenantCqbcPush.setCategoryId(categoryId);
        List<Map<String,String>> datalist=cqbcTuiSongMapper.getStatebyids(ids,tenantCqbcPush.getTableName());
        for (int i = 0; i <ids.size(); i++) {
            String cqbcState="";
            boolean flag=true;
            for (int j = 0; j < datalist.size(); j++) {
                Long mapid=Long.parseLong(String.valueOf(datalist.get(j).get("DATA_ID")));
                cqbcState=datalist.get(j).get("STATE");
                if(mapid.equals(ids.getLong(i))){
                    //判断是否已经打包了
                    if(!"".equals(cqbcState)) {//说明已经走过这个步骤
                        flag=false;
                        break;
                    }
                }
            }
            if(flag){
                //打包
                try{
                    String dhfilepath="";
                    String path=cspath+String.valueOf(ids.get(i))+ File.separator;
                    File packZip = new File(cspath + String.valueOf(ids.get(i)) + ".zip");
                    if(!packZip.exists()){
                        File file = new File(path);
                        if(file.exists()){
                            //删除目录重新生成
                            FileUtils.deleteQuietly(file);
                        }

                        handOverReceiveService.packXml(path,Long.parseLong(String.valueOf(ids.get(i))),type);
                        //打压缩包
                        for (File dhfile : file.listFiles()) {
                            dhfilepath=dhfile.getAbsolutePath();
                        }

                        ZipUtils.zip(dhfilepath,dhfilepath);
                        //生成后删除临时文件
                        FileUtils.deleteQuietly(new File(dhfilepath));
                    }

                    tenantCqbcPush.setPath(dhfilepath+ ".zip");
                    tenantCqbcPush.setState("已打包");
                    tenantCqbcPush.setDataId(Long.parseLong(String.valueOf(ids.get(i))));
                    cqbcTuiSongMapper.insert(tenantCqbcPush,tenantCqbcPush.getTableName());
                }catch (Exception e){
                    e.printStackTrace();
                    continue;
                }
            }

        }
    }

    @Override
    public void plsixing(JSONObject json) {
        JSONArray ids = json.getJSONArray("ids");
        String code=json.getString("code");
        TenantCqbcPush tenantCqbcPush=new TenantCqbcPush();
        List<Map<String,String>> datalist=cqbcTuiSongMapper.getStatebyids(ids,tenantCqbcPush.getTableName());
        for (int i = 0; i <ids.size() ; i++) {
            String cqbcState="";
            boolean flag=true;
            String path="";
            for (int j = 0; j < datalist.size(); j++) {
                Long mapid=Long.parseLong(String.valueOf(datalist.get(j).get("DATA_ID")));
                cqbcState=datalist.get(j).get("STATE");
                if(mapid.equals(ids.getLong(i))){
                    //判断状态了
                    if(!"已打包".equals(cqbcState)&&!"四性检测未通过".equals(cqbcState)) {//说明状态不对
                        flag=false;
                        path="";
                        break;
                    }else{
                        path=String.valueOf(datalist.get(j).get("PATH"));
                    }
                }
            }
            if(flag){
                //四性
                try{
                    Map map = detectionObjectService.detectionPackage(path, code, "2", "1");
                    Integer failNum=Integer.parseInt(map.get("failNum").toString());
                    if(failNum>0){
                        tenantCqbcPush.setState("四性检测未通过");
                    }else{
                        tenantCqbcPush.setState("四性检测通过");
                    }
                    tenantCqbcPush.setSixingId(Long.parseLong(String.valueOf(map.get("sxId"))));
                    tenantCqbcPush.setDataId(Long.parseLong(String.valueOf(datalist.get(i).get("DATA_ID"))));
                    cqbcTuiSongMapper.update(tenantCqbcPush,tenantCqbcPush.getTableName());
                }catch (Exception e){
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

}
